package com.knight.mybatis.example.type;

import cn.hutool.json.JSONUtil;
import com.knight.mybatis.example.entity.Comment;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 自定义TypeHanlder
 */
@MappedTypes(value = {Comment.class})
public class JsonTypeHandler extends BaseTypeHandler<Comment> {

    public JsonTypeHandler() {
        System.out.println("init JsonTypeHandler");
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Comment parameter, JdbcType jdbcType) throws SQLException {

        System.out.println("---------------[TypeHandler] setNonNullParameter------------");
        if (parameter != null) {
            ps.setString(i,JSONUtil.toJsonStr(parameter));
        }
    }

    @Override
    public Comment getNullableResult(ResultSet rs, String columnName) throws SQLException {
        System.out.println("---------------[TypeHandler] getNullableResult------------");
        String columnValue = rs.getString(columnName);
        System.out.println("column value:" + columnValue);
        Comment comment = JSONUtil.toBean(columnValue, Comment.class);
        System.out.println(comment);
        return comment;
    }

    @Override
    public Comment getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        System.out.println("---------------[TypeHandler] setNonNullParameter columnIndex------------");
        String columnValue = rs.getString(columnIndex);
        System.out.println("[TypeHandler] column value:" + columnValue);
        return null;
    }

    @Override
    public Comment getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        System.out.println("---------------setNonNullParameter callableStatement columnIndex------------");
        return null;
    }
}
